package com.hqq.concurrency.promise;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * PromiseSupport
 * Future的简单实现
 * Created by heqianqian on 2017/8/1.
 */
public class PromiseSupport<T> implements Future<T> {

    private static int RUNNING = 1;
    private static int FAILED = 2;
    private static int COMPLETED = 3;

    private volatile int state = RUNNING;
    private final Object lock;
    private T value;
    private Exception exception;

    public PromiseSupport() {
        this.lock = new Object();
    }

    void fulfill(T value) {
        this.value = value;
        this.state = COMPLETED;
        synchronized (lock) {
            lock.notifyAll();
        }
    }

    public void fulfillExceptionally(Exception exception) {
        this.exception = exception;
        this.state = FAILED;
        synchronized (lock) {
            lock.notifyAll();
        }
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return state > RUNNING;
    }

    @Override
    public T get() throws InterruptedException, ExecutionException {
        if (state == COMPLETED) {
            return value;
        } else if (state == FAILED) {
            throw new RuntimeException(exception);
        } else {
            synchronized (lock) {
                lock.wait();
                if (state == COMPLETED) {
                    return value;
                } else {
                    throw new ExecutionException(exception);
                }
            }
        }
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (state == COMPLETED) {
            return value;
        } else if (state == FAILED) {
            throw new RuntimeException(exception);
        } else {
            synchronized (lock) {
                lock.wait(unit.toMillis(timeout));
                if (state == COMPLETED) {
                    return value;
                } else if (state == FAILED) {
                    throw new RuntimeException(exception);
                } else {
                    throw new TimeoutException();
                }
            }
        }
    }

}
